<?php
namespace api\components;

use common\helpers\ExtendFunction;
use common\models\ARUser;
use linslin\yii2\curl\Curl;
use Yii;
use yii\base\Model;
use yii\base\InvalidParamException;
use yii\helpers\Json;

/**
 * api模型
 * @author CGA
 */
class ApiModel extends Model
{
    protected $_user;

    /*
     * 重写验证函数，有错即抛
     */
    public function validate($attributeNames = null, $clearErrors = true)
    {
        if ($clearErrors) {
            $this->clearErrors();
        }

        if (!$this->beforeValidate()) {
            return false;
        }

        $scenarios = $this->scenarios();
        $scenario = $this->getScenario();
        if (!isset($scenarios[$scenario])) {
            throw new InvalidParamException("Unknown scenario: $scenario");
        }

        if ($attributeNames === null) {
            $attributeNames = $this->activeAttributes();
        }

        foreach ($this->getActiveValidators() as $validator) {
            $validator->validateAttributes($this, $attributeNames);
            if ($this->hasErrors()) { //add
                return false; //add
            } //add
        }
        $this->afterValidate();

        return true; //modify
    }

    /**
     * 获取模型错误
     */
    public static function getErrorMessge($model, $isthrow = true)
    {
        $error = null;
        if ($model->hasErrors()) {
            $errors = $model->getErrors();
            foreach ($errors as $value) {
                $error = $value[0];
                break;
            }
        }
        if ($isthrow && !(null === $error)) {
            throw new ValidateException($error);
        } elseif (!$isthrow && !(null === $error)) {
            return $error;
        } else {
            return true;
        }
    }

    /**
     * 获取用户信息
     * @param string $uid 用户id
     */
    protected function getUser($uid = null)
    {
        if (null === $uid) {
            $uid = Yii::$app->user->id;
        }
        if (null === $this->_user) {
            $this->_user = ARUser::findOne($uid);
            if (null === $this->_user) {
                throw new ValidateException('无效用户');
            }
        }
        return $this->_user;
    }

    /**
     * 抛出错误
     */
    protected static function throwError($code, $message = null)
    {
        if (null === $message) {
            throw new OperateException($code);
        } else {
            throw new ValidateException($message);
        }
    }

    /**
     * 获取安全加密码
     */
    protected static function getSecurity($params, $addtime, $salt)
    {
        $params['salt'] = md5($salt);
        ksort($params);
        $str = ExtendFunction::array2str($params, '&') . $addtime;
        return strtoupper(md5($str));
    }

    /**
     * curl访问
     */
    public function curl($url, $params = [], $header = [], $method = 'post',$timeout=5)
    {
        $curl = new Curl();
        $result = $curl->setPostParams($params)
            ->setHeaders($header)
            ->setOption(CURLOPT_TIMEOUT, $timeout)
            ->setOption(CURLOPT_SSL_VERIFYPEER, false)
            ->setOption(CURLOPT_SSL_VERIFYHOST, false);
        if ($method == 'post') {
            $result = $result->post($url);
        } else {
            $result = $result->get($url);
        }
        $result = Json::decode($result);
        return $result;
    }
}
